package com.wtzz.police.base.service.impl;

import com.github.wenhao.jpa.Specifications;
import com.wtzz.police.base.bean.dto.OperationLogDto;
import com.wtzz.police.base.bean.req.OperationLogFilterDto;
import com.wtzz.police.base.entity.OperationLog;
import com.wtzz.police.base.entity.OperationLog_;
import com.wtzz.police.base.repository.OperationLogRepository;
import com.wtzz.police.base.service.OperationLogService;
import com.wtzz.police.base.util.component.MapperWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Service
@Slf4j
public class OperationLogServiceImpl implements OperationLogService {

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private OperationLogRepository repository;
    @Autowired
    private MapperWrapper mp;

    @Override
    public Page<OperationLogDto> list(Pageable pageable, OperationLogFilterDto filterDto) {
        Specification<OperationLog> spec;
        spec = Specifications.<OperationLog>and().eq(StringUtils.isNotBlank(filterDto.getIp()), OperationLog_.IP, filterDto.getIp())
                                                 .eq(StringUtils.isNotBlank(filterDto.getUserId()), OperationLog_.USER_ID, filterDto.getUserId())
                                                 .ge(filterDto.getStart() != null, OperationLog_.CREATED_DATE, filterDto.getStart())
                                                 .lt(filterDto.getEnd() != null, OperationLog_.CREATED_DATE, filterDto.getEnd())
                                                 .build();
        Page<OperationLog> p = repository.findAll(spec, pageable);
        return new PageImpl<>(mp.mapList(p.getContent(), OperationLogDto.class), pageable, p.getTotalElements());
    }
}
